module.exports = Behavior({
    methods: {
        /**上传文件通用方法 */
        afterRead(e) {
            const { field } = e.currentTarget.dataset
            const { file } = e.detail
            if (!Array.isArray(file)) { //为对象时
                file = [file]
            }
            let fieldList = this.data[field] || []
            fieldList = fieldList.concat(file)
            this.setData({
                [field]: fieldList
            })
            this.upload(field)
        },
        /**上传文件至服务器 */
        upload(field) {
            let that = this
            this.data[field].forEach((item, index) => {
                if (item.status === 'done') return
                this.setData({
                    [field + '[' + index + '].status']: 'uploading',
                    [field + '[' + index + '].message']: '上传中',
                })
                wx.uploadFile({
                    url: this.data.host + (item.type === 'video' ? '' : '/api/upload/image'),
                    filePath: item.url,
                    name: 'image',
                    formData: that.data[field + 'FormData'] || null,
                    header: {
                        Authorization: wx.getStorageSync('Authorization')
                    },
                    success(res) {
                        const data = JSON.parse(res.data)
                        if (data.code === 0) {
                            const { path } = data.data
                            that.setData({
                                [field + '[' + index + '].status']: 'done',
                                [field + '[' + index + '].uploadPath']: path
                            })
                        } else {
                            that.setData({
                                [field + '[' + index + '].status']: 'failed',
                                [field + '[' + index + '].message']: '上传失败',
                            })
                        }
                    },
                    fail() {
                        that.setData({
                            [field + '[' + index + '].status']: 'failed',
                            [field + '[' + index + '].message']: '上传失败'
                        })
                    }
                })
            })
        },
        /**删除文件 */
        uploadDel(e) {
            const { field } = e.currentTarget.dataset
            const { index } = e.detail
            let fieldList = this.data[field]
            fieldList.splice(index, 1)
            this.setData({
                [field]: fieldList
            })
        },
        /**文件大小限制提示 */
        uploadSizeOver(e) {
            const { max } = e.currentTarget.dataset
            wx.showToast({
                title: `上传文件大小不能超过${max}M`,
                icon: 'none',
                duration: 2000
            })
        }
    }
})